import json

import datetime
import os

from alipay import AliPay
from django import http
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.areas.models import Address
from apps.goods.models import SKU
from apps.orders.models import OrderInfo, OrderGoods
from utils.response_code import RETCODE
from django.db import transaction


class OrderSettlementView(LoginRequiredMixin,View):
    def get(self,request):
        user_id=request.user.id
        print(user_id)
        try:
            addresses=Address.objects.filter(user_id=user_id,is_deleted=False)
        except:
            addresses=None

        redis_client=get_redis_connection('carts')
        redis_data=redis_client.hgetall('carts_%d' %user_id)
        data_dict={}
        total_count=0
        total_amount=0
        for key,value in redis_data.items():
            sku_id=int(key.decode())
            values=json.loads(value.decode())
            sku=SKU.objects.get(id=sku_id)
            if values['selected']==True:
                data_dict[sku_id]=values


        skus=SKU.objects.filter(id__in=data_dict.keys())
        for sku in skus:
            sku.count = data_dict[sku.id].get('count')
            sku.amount = sku.count * sku.price
            # 计算总数量和总金额
            total_count += sku.count
            total_amount += sku.count * sku.price
        # 4.构建前端显示的数据
        context = {
            'addresses': addresses,
            'skus': skus,
            'total_count': total_count,
            'total_amount': total_amount,
            'freight': 10,
            'payment_amount': total_amount + 10,
            'default_address_id': request.user.default_address_id
        }
        return render(request, 'place_order.html', context)


class OrderCommitView(LoginRequiredMixin,View):
    def post(self,request):
        request_data=json.loads(request.body.decode())
        address_id=request_data.get('address_id')
        pay_method=request_data.get('pay_method')
        user=request.user
        print(user.id)
        #建立订单表

        order_id=datetime.datetime.now().strftime('%Y%m%d%H%M%S') + ('%09d' % user.id)
        with transaction.atomic():
            save_id = transaction.savepoint()
            order=OrderInfo.objects.create(
                order_id=order_id,
                user=user,
                address=Address.objects.get(id=address_id),
                total_count=0,
                total_amount=0,
                freight=10,
                pay_method=pay_method,
                status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'] if pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY'] else
                OrderInfo.ORDER_STATUS_ENUM['UNSEND']
            )
            #建立商品订单表
            redis_client=get_redis_connection('carts')
            redis_data=redis_client.hgetall('carts_%d' %user.id)
            values={}
            for key,value in redis_data.items():
                sku_id=int(key.decode())
                values=json.loads(value.decode())

                sku=SKU.objects.get(id=sku_id)
                if values['selected']==True:
                    if values['count'] > sku.stock:
                        transaction.savepoint_rollback(save_id)
                        return http.JsonResponse({'code': RETCODE.STOCKERR, 'errmsg': '库存不足'})
                    carts_count=values['count']

                    OrderGoods.objects.create(
                        order=order,
                        sku=sku,
                        count=carts_count,
                        price=sku.price,
                    )

                    order.total_count+=carts_count
                    sku.stock-=carts_count
                    sku.sales+=carts_count
                    sku.save()
                    sku.spu.sales+=carts_count
                    sku.spu.save()
                    order.total_amount+=sku.price*carts_count
            transaction.savepoint_commit(save_id)
            order.total_amount+=order.freight
            order.save()
        print('*'*12,user.id)
        redis_client.hdel('carts_%d' %user.id,*values)
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '下单成功', 'order_id': order.order_id})

class OrderSuccessView(LoginRequiredMixin,View):
    def get(self,request):
        """
        context = {
            'order_id':order_id,
            'payment_amount':payment_amount,
            'pay_method':pay_method
        }
        :param request:
        :return:
        """

        order_id=order_id = request.GET.get('order_id')



        payment_amount=request.GET.get('payment_amount')
        pay_method=request.GET.get('pay_method')
        context = {
            'order_id': order_id,
            'payment_amount': payment_amount,
            'pay_method': pay_method
        }
        return render(request,'order_success.html',context)

#我的订单
class OrdersInfo(LoginRequiredMixin,View):
    def get(self,request,page_num):
        """
        user_center_order.html

        context = {
            # 每页显示的内容
            "page_orders": page_orders,
            # 总页数
            'total_page': total_page,
            # 当前页
            'page_num': page_num,
        }
        page_orders:{
        orser_id:{
            sku
            }
        }
        :param request:
        :return:
        """
        user=request.user
        # ’sku‘：{
        #     商品名
        #单价
        #每种的个数
        #每种的总价格

        # }
        orders=user.orderinfo_set.all().order_by('-create_time')

        for order in orders:
            # 绑定订单状态
            order.status_name = OrderInfo.ORDER_STATUS_CHOICES[order.status - 1][1]
            # 绑定支付方式
            order.pay_method_name = OrderInfo.PAY_METHOD_CHOICES[order.pay_method - 1][1]
            order.sku_list = []

            order_goods=order.skus.all()
            for order_good in order_goods:
                sku=order_good.sku
                sku.count = order_good.count
                sku.amount = sku.price * sku.count
                order.sku_list.append(sku)



        page_num=int(page_num)



        # 获取每页商品数据
        try:
            paginator = Paginator(orders, 3)
            page_orders = paginator.page(page_num)
            # 获取列表页总页数
            total_page = paginator.num_pages
        except EmptyPage:
            # 如果page_num不正确，默认给用户404
            return http.HttpResponseNotFound('订单不存在')


        context={
            # 每页显示的内容
            "page_orders": page_orders,
            # 总页数
            'total_page': total_page,
            # 当前页
            'page_num': page_num,
        }

        return render(request,'user_center_order.html',context)

#评价页面
class OrdersComments(LoginRequiredMixin,View):
    #显示评价页面
    def get(self,request):
        """
          context = {
            'uncomment_goods_list': [
                {
                'order_id':goods.order.order_id,
                'sku_id':goods.sku.id,
                'name':goods.sku.name,
                'price':str(goods.price),
                'default_image_url':goods.sku.default_image.url,
                'comment':goods.comment,
                'score':goods.score,
                'is_anonymous':str(goods.is_anonymous),
                }
            ]

        }
        :param request:
        :return:
        """
        order_id=request.GET.get('order_id')
        uncomment_goods_list = []

        order=OrderInfo.objects.get(order_id=order_id)
        goodes=order.skus.all()
        for goods in goodes:
            uncomment_goods_list.append({
                'order_id': goods.order.order_id,
                'sku_id': goods.sku.id,
                'name': goods.sku.name,
                'price': str(goods.price),
                'default_image_url': goods.sku.default_image.url,
                'comment': goods.comment,
                'score': goods.score,
                'is_anonymous': str(goods.is_anonymous),
            })
        context={
            'uncomment_goods_list':uncomment_goods_list
        }
        return render(request,'goods_judge.html',context)
    #
    def post(self,request):
        """
        2.请求参数：Json参数

        参数名	类型	是否必传	说明
        order_id	int	是	订单编号
        sku_id	int	是	商品编号
        score	int	是	得分
        comment	int	是	评论
        is_anonymous	int	是	是否匿名评价
        :param request:
        :return:
        """
        data=json.loads(request.body.decode())
        order_id=data.get('order_id')
        sku_id=data.get('sku_id')
        score=data.get('score')
        comment=data.get('comment')
        is_anonymous=data.get('is_anonymous')
        #1改评分
        #2改评论
        #3是否匿名评价
        #4改is_commented
        try:
            goods=OrderGoods.objects.get(order_id=order_id,sku_id=sku_id)
        except:
            return http.HttpResponseForbidden('无此商品')
        goods.score=score
        goods.comment=comment
        goods.is_commented=1
        goods.is_anonymous=is_anonymous
        goods.save()
        goods.order.status=5
        goods.order.save()

        return http.JsonResponse({
            'code': RETCODE.OK,
             'errmsg': '评价成功'
        })

